package org.simp.core.body;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.simp.protocol.core.SimpleSimpBody.Paramter;
import org.simp.protocol.core.SimpleSimpBody.SimpleBody;

import com.google.protobuf.InvalidProtocolBufferException;

/**
 * @author zhuhaitao at 2014-5-26
 *
 * 简单key，value形式的协议消息体
 */
public class SimpleSimpBody implements SimpBody{

	private Map<String,String> params = new HashMap<String,String>();
	
	private SimpleBody body;
	
	private boolean hasModify;
	@Override
	public byte[] encode() {
		createBody();
		if(body == null){
			return new byte[0];
		}
		
		return body.toByteArray();
	}

	@Override
	public void decode(byte[] data) {
		try {
			body = SimpleBody.parseFrom(data);
		} catch (InvalidProtocolBufferException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void  createBody(){
		if(!hasModify){
			return ;
		}
		SimpleBody.Builder builder = SimpleBody.newBuilder();
		Set<String> keys = params.keySet();
		for(String key : keys){
		builder.addParamter(createParamter(key, params.get(key)));
		}
		body = builder.build();
		hasModify = false;
	}
	
	private Paramter createParamter(String key,String value){
		Paramter.Builder builder = Paramter.newBuilder();
		builder.setName(key);
		builder.setValue(value);
		return builder.build();
	}
	
	public void addParamter(String key,String value){
		params.put(key, value);
		hasModify = true;
	}
	public void removeParamter(String key){
		params.remove(key);
		hasModify = true;
	}
}
